#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;
typedef long long LL;
const int N = 5e3 + 10;
int f[N][N];
int n, m, k;
void insert(int x1, int y1, int x2, int y2, int t)
{
	f[x1][y1] += t; f[x2 + 1][y2 + 1] += t;
	f[x1][y2 + 1] -= t; f[x2 + 1][y1] -= t;
}
int main()
{
	cin >> n >> m >> k;
	for (int i = 1; i <= m; i++)
	{
		int x, y, t; cin >> x >> y >> t;
		insert(x, y, x, y, t);
	}
	LL ret = 0;
	for (int x1 = 1; x1 <= n - k + 1; x1++)
	{
		for (int y1 = 1; y1 <= n - k + 1; y1++)
		{
			int t = f[x1][y1];
			ret += abs(t);
			int x2 = x1 + k - 1, y2 = y1 + k - 1;
			insert(x1, y1, x2, y2, -t);

		}
	}
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			if (f[i][j] != 0)
			{
				cout << -1 << endl;
				return 0;
			}
	cout << ret << endl;
	return 0;
}